import twitterpic.*;
//import org.json.*;
import processing.video.*;
import processing.serial.*;

import java.text.SimpleDateFormat;
import java.util.Calendar;



Capture myCapture=null;

Twitter myTwitter;

int lastMinute;  
int lastHour;
int halfHourCounter=0;
String[] adminList = {"codejoy"};

String secretCode = "1234";

Serial myPort;  // Create object from Serial class
int val;      // Data received from the serial port
String sVal;
int lf=10;
boolean armed=false;
Date startupTime;

boolean cheatScreen;

static final int HAPPY=0;
static final int SAD=1;
static final int ANGRY=2;
static final int CONFUSED=3;
static final int CONTENT=4;


int requestsLastHour=0;
int tweetsSentLastHour=0;
int hrCount=0;
/* TODO: 
1) build a nice uUI in processing to see user list that is located on disk
2) build a user list on disk that is checked against every query of whose following, add those that are new followers to the list and then add them to follow.
3) Come up with neat games for users to play via twitter.
4) Display winners in glorious fashion as a screenshot, twitpicd.
5) Get Display monitors and print those out.
6) Design for end userusability.  Drop n Go. 
UI Must edit:
   Followers List
   ADMIN followers list
   Twitter Name/Password.

DEVELOP main lexicon for commands
  D tweetmicasa -status              -temperature 
    response:   current micassa temperature is TEMP
    
  D tweetmicasa -screenshot
  
  D tweetmicasa -help
            DM //send to tiny url the help page.
              Direct message with -screenshot, -status, -webcam, -play hangman
              more at: tinyurl://etc etc.
  D tweetmicasa -webcam                    -web cam shot
    response
                @requestor here is your tweet pic!
  D tweetmicasa -play battleship      -start a game of battleship with the casa
  D tweetmicasa -play hangman         -play hangman with the casa.  save for timng events etc
  D tweetmicasa -play x
  
  D tweetmicsa hi there               -response greeting
  
  D tweetmicasa rerequest             -rerequest

  ADMIN functions:
  D tweetmicasa -temp degrees         -set temp to degrees
  D tweetmicasa -shutdown             -shutdown micasa service
  D tweetmicasa -tweet msg            -send out a tweet that says msg

*/
int currentMood;
  int xd = 10;
  int yd = 20;
  int wid =50;
  int ht = 80;
  int posx;
  int posy;
  
  PFont fontA;
void setup() {
  
  size(800, 600);
  lastMinute=minute();
  setupTwitter();  
  
  fontA = loadFont("ArialMT-48.vlw");

  // Set the font and its size (in units of pixels)
  textFont(fontA, 32);
  wid=getWidth()/4;
  ht = getHeight()/3;
  currentMood=SAD;
  try {
    myCapture = new Capture(this, 320, 280, 60);
   }
    catch (Exception e) {
        println("Couldn't get cd: "  + e);
        myCapture=null;
    };
  
    String[] names = Serial.list();
    println("Here:");
    for(int i=0; i<names.length; i++)
    {
      println(names[i]);
    }
    
   
   
   myPort = new Serial(this, "COM3", 9600);
   myPort.bufferUntil(lf);  
   
   startupTime = new Date();

//   startupTime = now.getTimeInMillis();
   println(startupTime);
};

void captureEvent(Capture myCapture) {
  if(myCapture!=null)
    myCapture.read();
}

boolean adminCheck(User u)
{
   String name =u.getScreenName();
   for(int i=0; i< adminList.length; i++)
   {
      if(adminList[i].equals(name))
       return true; 
   }
  
   return false;
}

void setupTwitter()
{
  //send direct messages from twitter
  // d + username + message
  
  myTwitter = new Twitter("admin@tweetmicasa.com", "stwins1"); //houses here
  checkUsers();
   
  /* sample twitter usage */
  /* 
   try {
      Query query = new Query("love");
      QueryResult result = myTwitter.search(query);   

      Paging page = new Paging(1);
      ArrayList statuses = (ArrayList) myTwitter.getHomeTimeline(page);
      for (int i = 0; i < statuses.size(); i++) {
        Status s = (Status) statuses.get(i);
        String user = s.getUser().getName();
        String msg = s.getText();
         Date d = s.getCreatedAt();
        println("Tweet by " + user + " at " + d + ": " + msg);
      };
//      myTwitter.updateStatus("@shanetphotog testing my new twitter code!");
//      myTwitter.sendDirectMessage("normaelsa", "Hi!  Sent from computer code :)");
       println("--");
      ArrayList dmsgs = (ArrayList)myTwitter.getDirectMessages();
      
      for(int i=0; i<dmsgs.size(); i++)
      {
         DirectMessage dm = (DirectMessage) dmsgs.get(i);
         println("DirectMessage From: " + dm.getSender().getName() + " To: " + dm.getRecipient().getName() + ": " + dm.getText());        
        
      }
     
    }
    catch (TwitterException te) {
        println("Couldn't connect: " + te);
    };
    */
}

void serialEvent(Serial p) {
  String inString;
  
  inString = (myPort.readString());
  println(inString);
  String alarm = inString.substring(0, 8);
  if(alarm.equals("---ALARM"))
  {
    if(armed)
      sendEmergencyTweet(inString);
  }   
    
  
}

void sendEmergencyTweet(String data) 
{
    String url = "http://twitpic.com/api/uploadAndPost";

    ImageToTwitter img = new ImageToTwitter(this);

    size(340,280);
    set(0, 0, myCapture);
    img.post(url,"jpg-test","tweetmicasa", "stwins1", data, true, img.getBytes(g)); 
    size(800,600);
      tweetsSentLastHour++;
    for(int i=0; i< adminList.length; i++)
     {
        try {
               myTwitter.sendDirectMessage(adminList[i], "ALARM: " + data);
                   tweetsSentLastHour++;
        }
        catch(TwitterException te)
        {
            println("ERror: " + te);
        }
     }
}

/**
 * Handle key presses:
 * 'c' toggles the cheat screen that shows the original image in the corner
 * 'g' grabs an image and saves the frame to a tiff image
 * 'f' and 'F' increase and decrease the font size
 */
public void keyPressed() {
  switch (key) {
    case 'c': cheatScreen = !cheatScreen; break;
    case 'f': handleDirectMessages(); break;
  }
}

void drawMood()
{
  switch(currentMood)
  {
    case HAPPY: 
      drawSmileyFace();
      break;
    case SAD:
      drawSadFace();
      break;
  
  }
  
}

void drawSmileyFace()
{
  background(0,200,200);
  smiley(getWidth()/2,getHeight()/2,wid,ht);
}

void drawSadFace()
{
   background(0,0,200);
   frowny(getWidth()/2,getHeight()/2,wid,ht);
  
}

void frowny(int x,int y,int w,int h) {
   fill(255,255,255); //white
   ellipse(x,y,w,h);
   noFill();
   arc(x,y,w/2,h/2,.25*PI,PI*.75);
   fill(0,0,0);  //black
   ellipse(x-w*.25,y-h*.25,w/10,h/10);
   ellipse(x+w*.25,y-h*.25,w/10,h/10);
}
 
void smiley(int x,int y,int w,int h) {
   fill(255,255,255); //white
   ellipse(x,y,w,h);
   noFill();
   arc(x,y,w/2,h/2,.25*PI,PI*.75);
   fill(0,0,0);  //black
   ellipse(x-w*.25,y-h*.25,w/10,h/10);
   ellipse(x+w*.25,y-h*.25,w/10,h/10);
}

void drawStats()
{
  
  Date now = new Date();
   long diff = now.getTime() - startupTime.getTime();

  long days = (diff/(1000*60*60*24));
  long hrs = (diff/(1000*60*60));
  long minutes = (diff/(1000*60));
  long seconds = (diff/1000);

  String difference = days + " days " + hrs + " hrs" + minutes + " minutes" + seconds + " seconds";

   textFont(fontA, 12);
   text("Up Time:" , 10, 10);
   text(difference, 50, 30);
   textFont(fontA, 32);
   text("Stats: " , 100,100);  
}

void draw() {

  drawMood();
  drawStats();

  if (cheatScreen) {
    //image(video, 0, height - video.height);
    // set() is faster than image() when drawing untransformed images
    set(0, height - myCapture.height, myCapture);
    //image(myCapture, 0, 0);
  }



  //hanndle twitter updates
  if(minute() !=lastMinute)
  {
    println("last minute: " + lastMinute);
    println("Running checks...");
    halfHourCounter++;
    if(halfHourCounter>=30)
    {
       halfHourCounter=0;
       checkUsers();//4 calls possible every 1/2hour
       hrCount++;
       if(hrCount>2)
       {
          hrCount=0;
          requestsLastHour=0;
          tweetsSentLastHour=0;
       }
    }
    handleDirectMessages();      
    

    lastMinute=minute();
      /* handle mentions */
      //not sure what to do here.
    println("Checks done...");
  }
      
};

void handleDirectMessages()
{
  
  ArrayList dmsgs = new ArrayList();
  try {
    dmsgs = (ArrayList)myTwitter.getDirectMessages();    
  } 
  catch( TwitterException te)
  {
    println("Error getting direct emssages: " +  te);
  }
  
  
  if(dmsgs.size()<=0)
    return;
  
  requestsLastHour+=dmsgs.size();
    
  for(int i=0; i<dmsgs.size(); i++)
  {
          DirectMessage dm = (DirectMessage) dmsgs.get(i);
          parseDM(dm);          
  }  
}

String getTimeStamp()
{
  Date now = new Date();
  return now.toString(); 
}


void parseDM(DirectMessage dm)
{
//  User sender = dm.getSender();
  
  String message = dm.getText();
  
 // String phrase = "-status -temp hi there!";
  String delims = "[ ]+";
  String[] tokens = message.split(delims);

  if(tokens[0].equals("-webcam"))
  {
//    Image capimg = myCapture.getImage();
    String url = "http://twitpic.com/api/uploadAndPost";

    ImageToTwitter img = new ImageToTwitter(this);
    String mention = "@"+dm.getSender().getScreenName() + " your wish is my command!";
    size(340,280);
    set(0, 0, myCapture);


    img.post(url,"jpg-test","tweetmicasa", "stwins1", mention, true, img.getBytes(g)); 
    size(800,600);
    println("SENT IMAGE!");
    tweetsSentLastHour++;
  }
  else if(tokens[0].equals("-help"))
  {
      String helptxt= "Cmmds: -webcam, -status -temp, -plant, -computer, -screenshot";
      try {
        myTwitter.sendDirectMessage(dm.getSender().getScreenName(), helptxt);
      } catch(TwitterException te)
      {
        println("Error: " + te);
      }
      
      println("help sent to: " + dm.getSender().getScreenName());
          tweetsSentLastHour++;
  }
  else if(tokens[0].equals("-mention"))
  {
     //send a mention out! 
  
     try {
       String person = dm.getSender().getScreenName();
       myTwitter.updateStatus("I wanna send an awesome shoutout to @"+person + " ! Thanks for tweeting mi casas!");
     }
     catch(TwitterException te)
     {
       println("Error: " + te);
     }
         tweetsSentLastHour++;
  }
  else if(tokens[0].equals("-cocktail"))
  {
    println("sending cocktail status..."); //check next few tokens
    if(tokens[1].equals("-usa"))
    {
      //parse usa feed send top story and clip
    }
    else if(tokens[1].equals("-world"))
    {
      
    }
    else if(tokens[1].equals("-sports"))
    {
      
    }
  }
  else if(tokens[0].equals("-weather"))
  {
     String zipCode = tokens[1]; 
//     "feed: " http://rss.accuweather.com/rss/liveweather_rss.asp?metric=0&locCode=zipCode 
  }
  else if(tokens[0].equals("-status"))
  {
    println("sending status... tokens: " + tokens.length); //check next few tokens
    if(tokens.length>=2)
    {
      if(tokens[1].equals("-temp") || tokens[1].equals("-temperature"))
      {
        try {
            myTwitter.sendDirectMessage(dm.getSender().getScreenName(), "sorry not working yet");
        }
        catch(TwitterException te)
        {
          println("ERror: " + te);
        }
        println(" The current indoor temp is: " + 75 + " degrees");
            tweetsSentLastHour++;
      }
      else if(tokens[1].equals("-plant"))
      {
        try {
          myTwitter.sendDirectMessage(dm.getSender().getScreenName(), "sorry not working yet");
        }catch(TwitterException te)
        {
          println("ERror: " + te);
        }      
            tweetsSentLastHour++;
      }
      else if(tokens[1].equals("-computer"))
      {
        try {
          String statusMsg = "Computer up time: " + startupTime;
          myTwitter.sendDirectMessage(dm.getSender().getScreenName(), statusMsg);
        }catch(TwitterException te)
        {
          println("Error: " + te);
        }
            tweetsSentLastHour++;
      }
      else if(tokens[1].equals("-alarm"))
      {
        if(!adminCheck(dm.getSender()))
          return;
        
        if(armed)
         {
             try {
                myTwitter.sendDirectMessage(dm.getSender().getScreenName(), "SYSTEM IS ARMED!");
              }catch(TwitterException te)
              {
                println("Error: " + te);
              }
         }
         else
         {
             try {
                 myTwitter.sendDirectMessage(dm.getSender().getScreenName(), "SYSTEM IS DISARMED!");
              }catch(TwitterException te)
              {
                println("Error: " + te);
              }
         }
             tweetsSentLastHour++;
      }
    }
  }
  else if(tokens[0].equals("-screenshot"))
  {
    println("sending screen shot...");
    PImage simage = getScreen();
    String url = "http://twitpic.com/api/uploadAndPost";

    ImageToTwitter img = new ImageToTwitter(this);
    String mention = "@"+dm.getSender().getScreenName() + " What im up to!";
    size(simage.width, simage.height);
    set(0, 0, simage);    
    img.post(url,"jpg-test","tweetmicasa", "stwins1", mention, true, img.getBytes(g)); 
    size(800, 600);
    println("SENT Screenshot IMAGE!");
        tweetsSentLastHour++;
    
  }
  else if(tokens[0].equals("-arm"))
  {
    if(!adminCheck(dm.getSender()))
      return;
    if(!tokens[1].equals(secretCode))
     return;

    armed=true;
    try {
      myTwitter.sendDirectMessage(dm.getSender().getScreenName(), "system is ARMED");        
    }
    catch(TwitterException te)
    {
      println("ERROR: " + te);
    }
    println("system armed at: " + getTimeStamp());
        tweetsSentLastHour++;
  }
  else if(tokens[0].equals("-disarm"))
  {
     if(!adminCheck(dm.getSender()))
      return;
    if(!tokens[1].equals(secretCode))
     return;
     armed=false;
     try {
       myTwitter.sendDirectMessage(dm.getSender().getScreenName(), "system is DISarmed");        
     }
     catch(TwitterException te)
     {
       println("ERROR: " + te);
     }
     println("system DISarmed at: " + getTimeStamp());
         tweetsSentLastHour++;
  }
  else if(tokens[0].equals("-temp"))
  {
    if(!adminCheck(dm.getSender()))
      return;
  if(!tokens[1].equals(secretCode))
     return;      
//    setTemp(Integer.parseInt(tokens[1]));    
    println("ADMIN CHECK:  Set temp");
        tweetsSentLastHour++;
  }
  else if(tokens[0].equals("-shutdown"))
  {
    
     if(!adminCheck(dm.getSender()))
        return;
    if(!tokens[1].equals(secretCode))
         return;    
     println("Shut down received! night night");    
     try {
       String person = dm.getSender().getScreenName();
       myTwitter.updateStatus("@"+person + ", NO DISASSEMBLE JOHNNY 5! " + getTimeStamp());
       //twit pic random drawing here sad face drawing
     }
     catch(TwitterException te)
     {
       println("Error: " + te);
     }
      tweetsSentLastHour++;
      killBill(); //buh bye!
  
  }
  else if(tokens[0].equals("-tweet"))
  {
    if(!adminCheck(dm.getSender()))
      return;
     
    if(!tokens[1].equals(secretCode))
       return;     
    String tweetToSend="";
    for(int i=1; i<=tokens.length; i++)
    {
       tweetToSend=tweetToSend+tokens[i]; 
    }
    //sendTweet(tweetToSend);
    tweetsSentLastHour++;
    
  }
  else
     println("not recognized: " + tokens[0]);

    
  //if handled no errors
  deleteDM(dm);  
}

void killBill() {
  try {
    Runtime.getRuntime().exec("shutdown.exe -s -f -t 0");
  } 
  catch (IOException e) {
    e.printStackTrace();
  }

}

void deleteDM(DirectMessage dm)
{
  try {
     myTwitter.destroyDirectMessage(dm.getId());  
  }
  catch(TwitterException te)
  {
    println("Error : " + te);
  }
}

PImage getScreen() {
  GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
  GraphicsDevice[] gs = ge.getScreenDevices();
  DisplayMode mode = gs[0].getDisplayMode();
  Rectangle bounds = new Rectangle(0, 0, mode.getWidth(), mode.getHeight());
  BufferedImage desktop = new BufferedImage(mode.getWidth(), mode.getHeight(), BufferedImage.TYPE_INT_RGB);

  try {
    desktop = new Robot(gs[0]).createScreenCapture(bounds);
  }
  catch(AWTException e) {
    System.err.println("Screen capture failed.");
  }

  return (new PImage(desktop));
}

void checkUsers()
{
   
   //user = createFriendShip(name, true);
  
  
      //tw 
      IDs followers=null;
      IDs friends=null;
      try {
          followers= myTwitter.getFollowersIDs(); //who is following me
          friends = myTwitter.getFriendsIDs(); //who i am following 
       }
       catch(Exception e)
       {
          println("OUCH Exception: " + e); 
          return;
         
       }
    
      int[] intfollowers = followers.getIDs();
      int[] intfriends = friends.getIDs();
       sort(intfollowers);      
       sort(intfriends);
       boolean hit=false;
      //quick check
      
                //need to remove some
                println("Followers : " + intfollowers.length);
                println("Friends: " + intfriends.length);
                if(intfollowers.length < intfriends.length)
                {
                    for(int i=0; i<intfriends.length; i++)
                      {
                         for(int j=0; j<intfollowers.length; j++)
                         {
                            if(intfriends[i]==intfollowers[j])
                            {
                               hit=true;               
                               println("yah im following: " + intfollowers[j]);
                            }               
                         }
                         if(!hit)
                         {                          
                           try {
                              myTwitter.destroyFriendship(Integer.toString((intfriends[i])));
                           }
                           catch(TwitterException te)
                           {
                             println("Could not destroy friendship! with: " + intfriends[i] + ", ex:" + te);
                           }
                            
                         }
                      }
                }
                else if(intfollowers.length>intfriends.length) //need to add some
                {
                   for(int i=0; i<intfollowers.length; i++)
                      {
                        println("checking : " + intfollowers[i]);
                         for(int j=0; j<intfriends.length; j++)
                         {
                           println("against: " + intfriends[j]);
                            if(intfollowers[i]==intfriends[j])
                            {
                               hit=true;               
                               println("yah bro  following: " + intfollowers[i]);
                            }               
                         }
                         if(!hit)
                         {
                            try {
                              myTwitter.createFriendship(Integer.toString((intfollowers[i])));
                            }
                            catch(TwitterException te)
                            {
                              println("Could not create freindship with: " + intfollowers[i] + ", ex: " + te);
                            }
                            
                         }
                      }               
                }
          }
          catch(Exception e)
          {
            println("OUCH! " + e); 
          }
}
 
ArrayList loadUsers()
{
 	
    BufferedReader reader;
    int inline;
   
   String[] users = loadStrings("users.txt");
    ArrayList retusers=new ArrayList();
   if(users!=null)
   {
    
     for(int i=0; i<users.length; i++)
     {
       retusers.add(users[i]);
     }
   }

  
  // Open the file from the createWriter() example
 
  return retusers;

}

void keyPressed()
{

  /*String url = "http://twitpic.com/api/uploadAndPost";

    ImageToTwitter img = new ImageToTwitter(this);
    img.save("jpg",true);
    img.post(url,"jpg-test","tweetmicasa", "stwins123456!", "Mi Casa!", true, img.getBytes(g)); */  
  
    
};

